import {
  addUser,
  deleteUser,
  qryUserDetail,
  qryUserListPage,
  updateUser,
} from '@/services/user';
import { PlusOutlined } from '@ant-design/icons';
import type { ActionType, ProColumns } from '@ant-design/pro-components';
import { PageContainer, ProTable } from '@ant-design/pro-components';
import { Button, Form, Input, message, Modal, Popconfirm } from 'antd';
import React, { useRef, useState } from 'react';

interface UserItem {
  userId: string;
  userName: string;
  account: string;
  password: string;
  createDate: string;
}

const UserPage: React.FC = () => {
  const actionRef = useRef<ActionType>();
  const [form] = Form.useForm();
  const [modalVisible, setModalVisible] = useState(false);
  const [currentUser, setCurrentUser] = useState<UserItem | null>(null);
  const [confirmLoading, setConfirmLoading] = useState(false);

  const handleDelete = async (userId: string) => {
    try {
      await deleteUser({ userId });
      message.success('删除成功');
      actionRef.current?.reload();
    } catch (error) {
      message.error('删除失败');
    }
  };

  const handleEdit = async (userId: string) => {
    try {
      const detail = await qryUserDetail({ userId });
      setCurrentUser(detail);
      form.setFieldsValue(detail);
      setModalVisible(true);
    } catch (error) {
      message.error('获取详情失败');
    }
  };

  const columns: ProColumns<UserItem>[] = [
    {
      title: '用户编号',
      dataIndex: 'userId',
      key: 'userId',
      hideInSearch: true,
      width: 200,
    },
    {
      title: '用户名称',
      dataIndex: 'userName',
      key: 'userName',
    },
    {
      title: '账号',
      dataIndex: 'account',
      key: 'account',
    },
    {
      title: '创建时间',
      dataIndex: 'createDate',
      key: 'createDate',
      hideInSearch: true,
      width: 180,
    },
    {
      title: '操作',
      key: 'action',
      width: 150,
      valueType: 'option',
      render: (_, record) => [
        <Button
          key="edit"
          type="link"
          onClick={() => handleEdit(record.userId)}
        >
          编辑
        </Button>,
        <Popconfirm
          key="delete"
          title="确定要删除这个用户吗?"
          onConfirm={() => handleDelete(record.userId)}
          okText="确定"
          cancelText="取消"
        >
          <Button type="link" danger>
            删除
          </Button>
        </Popconfirm>,
      ],
    },
  ];

  const handleAdd = () => {
    form.resetFields();
    setCurrentUser(null);
    setModalVisible(true);
  };

  const handleSubmit = async () => {
    try {
      const values = await form.validateFields();
      setConfirmLoading(true);

      if (currentUser) {
        await updateUser({
          ...values,
          userId: currentUser.userId,
        });
        message.success('更新成功');
      } else {
        await addUser(values);
        message.success('新增成功');
      }

      setModalVisible(false);
      actionRef.current?.reload();
    } catch (error) {
      message.error('操作失败');
    } finally {
      setConfirmLoading(false);
    }
  };

  return (
    <PageContainer>
      <ProTable<UserItem>
        actionRef={actionRef}
        rowKey="userId"
        columns={columns}
        request={async (params) => {
          const { current, pageSize, ...rest } = params;
          console.log(rest);
          const result = await qryUserListPage({
            pageIndex: current,
            pageSize,
            param: {
              userName: rest.userName,
              account: rest.account,
            },
          });
          return {
            data: result.list,
            total: result.total,
            success: true,
          };
        }}
        toolBarRender={() => [
          <Button
            key="add"
            type="primary"
            icon={<PlusOutlined />}
            onClick={handleAdd}
          >
            新增用户
          </Button>,
        ]}
      />

      <Modal
        title={currentUser ? '编辑用户' : '新增用户'}
        open={modalVisible}
        onOk={handleSubmit}
        confirmLoading={confirmLoading}
        onCancel={() => setModalVisible(false)}
        width={600}
      >
        <Form form={form} layout="vertical">
          {currentUser && (
            <Form.Item name="userId" label="用户编号" hidden>
              <Input disabled />
            </Form.Item>
          )}
          <Form.Item
            name="userName"
            label="用户名称"
            rules={[{ required: true, message: '请输入用户名称' }]}
          >
            <Input placeholder="请输入用户名称" />
          </Form.Item>

          <Form.Item
            name="account"
            label="账号"
            rules={[{ required: true, message: '请输入账号' }]}
          >
            <Input placeholder="请输入账号" />
          </Form.Item>

          <Form.Item
            name="password"
            label="密码"
            rules={[{ required: true, message: '请输入密码' }]}
          >
            <Input.Password placeholder="请输入密码" />
          </Form.Item>
        </Form>
      </Modal>
    </PageContainer>
  );
};

export default UserPage;
